package main

import (
	"flag"
	"github.com/soheilhy/cmux"
	pb "go-programming-tour-book/grpc-demo/proto"
	"go-programming-tour-book/grpc-demo/server"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"log"
	"net"
	"net/http"
)

var port string

func init() {
	flag.StringVar(&port, "port", "8100", "启动端口")
	flag.Parse()
}

func main() {
	l, err := RunTcpServer(port)

	if err != nil {
		log.Fatalf("Run tcp fail:%v", err)
	}

	m := cmux.New(l)

	grpcL := m.MatchWithWriters(
		cmux.HTTP2MatchHeaderFieldPrefixSendSettings(
			"content-type",
			"application/grpc",
		),
	)

	httpL := m.Match(cmux.HTTP1Fast())

	grpcS := RunGrpcServer()

	httpS := RunHttpServer(port)

	go grpcS.Serve(grpcL)

	go httpS.Serve(httpL)

	err = m.Serve()

	if err != nil {
		log.Fatalf("Run server err :%v", err)
	}
}

//tcp服务
func RunTcpServer(port string) (net.Listener, error) {
	return net.Listen("tcp", ":"+port)
}

//http服务
func RunHttpServer(port string) *http.Server {
	serveMux := http.NewServeMux()

	serveMux.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("pong"))
	})

	return &http.Server{
		Addr:    ":" + port,
		Handler: serveMux,
	}
}

//grpc服务
func RunGrpcServer() *grpc.Server {
	s := grpc.NewServer()

	pb.RegisterTagServiceServer(s, server.NewTagServer())

	//注册反射服务
	reflection.Register(s)

	return s
}
